package com.uchedao.seller.ui.car.publish;

import android.app.AlertDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.nostra13.universalimageloader.utils.L;
import com.uchedao.seller.R;
import com.uchedao.seller.config.Api;
import com.uchedao.seller.config.GlobalInfo;
import com.uchedao.seller.http.HttpRequest;
import com.uchedao.seller.http.entity.PhotoEntity;
import com.uchedao.seller.inf.IOnResultBack;
import com.uchedao.seller.manager.ActivityManager;
import com.uchedao.seller.module.AttachInfo;
import com.uchedao.seller.module.BaseInfo;
import com.uchedao.seller.module.ConfigInfo;
import com.uchedao.seller.module.Draft;
import com.uchedao.seller.module.Photo;
import com.uchedao.seller.module.ResultIntArrayPics;
import com.uchedao.seller.module.Skeleton;
import com.uchedao.seller.ui.car.base.BasePublishActivity;
import com.uchedao.seller.ui.car.publish.baseinfo.UpLoadCarPicture;
import com.uchedao.seller.util.Arith;
import com.uchedao.seller.util.CoverImageUtil;
import com.uchedao.seller.util.ProgressDialogUtil;
import com.uchedao.seller.util.T;
import com.uchedao.seller.util.ToastUtil;
import com.uchedao.seller.util.UploadPicUtil;
import com.uchedao.seller.util.Util;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 发布4-车辆照片
 */
public class PublishPhotoActivity extends BasePublishActivity implements View.OnClickListener {

    private UpLoadCarPicture contentView;

    private UploadPicUtil upUtil;

    private boolean isUploading = false;

    private boolean isResume;

    @Override
    protected String getActivityTag() {
        return "PublishPhotoActivity";
    }

    @Override
    protected int getLayoutResID() {
        return R.layout.activity_publish_photo;
    }

    @Override
    protected void initView() {
        initToBar("车辆照片");
        initBottomBar();
        btnBottomNext.setText("下一步:竞拍规则");

        contentView = new UpLoadCarPicture(this);
        ((RelativeLayout) findViewById(R.id.rlPublishContent)).addView(contentView);

        upUtil = new UploadPicUtil(this);
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void initListener() {
        btnButtomSave.setOnClickListener(this);
        btnBottomNext.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch(view.getId()) {
            case R.id.btnPublishSave:
                contentView.save();
                ActivityManager.getInstance().clearAllActivity(null);
                break;

            case R.id.btnPublishNext:
                contentView.save();
                submit();
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        ((IOnResultBack) contentView).onActivityResultView(requestCode, resultCode, data);
    }

    /**
     * 提交验车报告
     *
     * 提交验车报告前，先上传车检照片，上传顺序:
     * 配置单(若有)->漆膜厚度示意图->结构检测示意图->漆面异常照片（若有）->外观异常照片（若有）
     * ->内饰异常照片(若有)->结构件异常照片(若有)->车辆照片
     */
    public void submit() {
        if(isUploading) {
            T.showShort(this, "正在提交");
            return;
        }

        if(GlobalInfo.draft.photo[0] == null) {
            // 行驶证为空
            T.showShort(this, "请选择行驶证");
            return;
        }

        ProgressDialogUtil.showProgressDlg(this, "提交验车报告...");
        isUploading = true;

        final AttachInfo attchInfo = GlobalInfo.draft.base_info.attach_info;
        if("有".equals(attchInfo.config_form)) {
            // 上传配置单图片
            UploadPicUtil.UpSinglePicCallback callback = new UploadPicUtil.UpSinglePicCallback() {
                @Override
                public void uploadCallback(boolean isSucceed, String result, String moduleName) {
                    if(isSucceed) {
                        attchInfo.config_form_url = result;
                        uploadPaintCover();
                    } else {
                        isUploading = false;
                        ProgressDialogUtil.dismissProgressDlg();
                        showFailDialog("配置单图片上传失败");
                    }
                }
            };
            upUtil.upSinglePic("", attchInfo.config_form_path, callback);
        } else {
            uploadPaintCover();
        }
    }

    /**
     * 上传漆膜厚度示意图
     */
    private void uploadPaintCover() {
        ImageView iv = new ImageView(this);
        Bitmap hasFix = CoverImageUtil.createPaintCoverView(GlobalInfo.draft.condition.paint_thickness, iv);

        File file = new File(GlobalInfo.PIC_PATH, System.currentTimeMillis() + ".jpg");
        try {
            Util.saveBitmap2File(hasFix, file);
        } catch (IOException e) {
            e.printStackTrace();
            isUploading = false;
            ToastUtil.showToastLong("保存漆膜检测示意图失败:" + e.getMessage());
            return;
        }

        String filePath = file.getAbsolutePath();
        UploadPicUtil.UpSinglePicCallback callback = new UploadPicUtil.UpSinglePicCallback() {
            @Override
            public void uploadCallback(boolean isSucceed, String result, String moduleName) {
                System.out.println("isSucceed:" + isSucceed + ";result:" + result);
                if (isSucceed) {
                    System.out.println("=== 漆膜 === OK");
                    GlobalInfo.draft.condition.paintPicUrl = result;
                    uploadkeletonCover();
                } else {
                    isUploading = false;
                    ProgressDialogUtil.dismissProgressDlg();
                    showFailDialog("漆膜厚度示意图上传失败");
                }
            }
        };
        System.out.println("上传漆膜厚度示意图");
        upUtil.upSinglePic("漆膜厚度示意图", filePath, callback);
        if (hasFix != null)
            hasFix.recycle();
    }

    /**
     * 上传结构检测示意图
     */
    private void uploadkeletonCover() {
        Bitmap bitmap = CoverImageUtil.getSkeletonCoverBitmap(this, GlobalInfo.draft.accident.skeletons);
        if (bitmap == null) {
            isUploading = false;
            return;
        }
        File file = new File(GlobalInfo.PIC_PATH, System.currentTimeMillis() + ".jpg");
        L.w("filePath = " + file.getAbsolutePath());
        try {
            Util.saveBitmap2File(bitmap, file);
        } catch (IOException e) {
            e.printStackTrace();
            ToastUtil.showToastLong("保存结构检测示意图失败:" + e.getMessage());
            isUploading = false;
            return;
        }

        String filePath = file.getAbsolutePath();
        UploadPicUtil.UpSinglePicCallback callback = new UploadPicUtil.UpSinglePicCallback() {
            @Override
            public void uploadCallback(boolean isSucceed, String result, String moduleName) {
                System.out.println("isSucceed:" + isSucceed + ";result:" + result);
                if (isSucceed) {
                    System.out.println("=== 结构 === OK");
                    GlobalInfo.draft.accident.skeletonPicUrl = result;
                    uploadPhoto(1, GlobalInfo.draft.condition.paint_surface);
                } else {
                    isUploading = false;
                    ProgressDialogUtil.dismissProgressDlg();
                    showFailDialog("结构检测示意图上传失败");
                }
            }
        };
        System.out.println("上传结构检测示意图");
        upUtil.upSinglePic("结构检测示意图", filePath, callback);
        if (bitmap != null)
            bitmap.recycle();
    }

    private int photoCount; // 待上传照片数
    private boolean isUpSucceed;   // 照片上传是否成功

    /**
     * @param step
     * 1 漆面  2 外观  3 内饰
     */
    public void uploadPhoto(final int step, final ResultIntArrayPics[] resultIntArrayPics) {
        photoCount = 0;
        isUpSucceed = true;

        for(ResultIntArrayPics arrayPic : resultIntArrayPics) {
            if(arrayPic == null)
                continue;
            photoCount += arrayPic.pic_path_list.size();
        }

        if(photoCount <= 0) {   // 无异常图片
            uploadNextStep(true, step);
        } else {    // 上传异常图片
            String filePath = null;
            // 上传漆面检测图片
            for (final ResultIntArrayPics arrayPic : resultIntArrayPics) {
                if (arrayPic == null) {
                    L.i("arrayPic==null");
                    continue;
                }

                arrayPic.pic_url_list.clear();
                for (int i = 0; i < arrayPic.pic_path_list.size(); i++) {
                    filePath = arrayPic.pic_path_list.get(i);

                    final String finalFilePath = filePath;
                    UploadPicUtil.UpSinglePicCallback callback = new UploadPicUtil.UpSinglePicCallback() {
                        @Override
                        public void uploadCallback(boolean isSucceed, String result, String moduleName) {
                            System.out.println("isSucceed:" + isSucceed + ";result:" + result);
                            photoCount--;
                            if (isSucceed) {
                                arrayPic.pic_url_list.add(result);
                            } else {
                                isUpSucceed = false;
                            }

                            if(photoCount <= 0)
                                uploadNextStep(isUpSucceed, step);

                        }
                    };
                    System.out.println("上传"+arrayPic.name);
                    upUtil.upSinglePic("综合检测照片", filePath, callback);
                }
            }
        }
    }

    /**
     * 上传结构件照片
     * @param step
     * @param skeletons
     */
    private void uploadPhoto(final int step, final Skeleton[] skeletons) {
        photoCount = 0;
        isUpSucceed = true;

        for(Skeleton skeleton : skeletons) {
            if(skeleton == null)
                continue;
            photoCount += skeleton.pic_path_list.size();
        }

        if(photoCount <= 0) {   // 无异常图片
            uploadNextStep(true, step);
        } else {    // 上传异常图片
            String filePath = null;
            for (final Skeleton skeleton : skeletons) {
                if (skeleton == null) {
                    L.i("skeleton==null");
                    continue;
                }
                skeleton.pic_url_list.clear();
                for (int i = 0; i < skeleton.pic_path_list.size(); i++) {
                    filePath = skeleton.pic_path_list.get(i);

                    final String finalFilePath = filePath;
                    UploadPicUtil.UpSinglePicCallback callback = new UploadPicUtil.UpSinglePicCallback() {
                        @Override
                        public void uploadCallback(boolean isSucceed, String result, String moduleName) {
                            System.out.println("isSucceed:" + isSucceed + ";result:" + result);
                            photoCount--;
                            if (isSucceed) {
                                skeleton.pic_url_list.add(result);
                            } else {
                                isUpSucceed = false;
                            }

                            if (photoCount <= 0)
                                uploadNextStep(isUpSucceed, step);
                        }
                    };
                    System.out.println("上传"+skeleton.name);
                    upUtil.upSinglePic("结构件图片", filePath, callback);
                }
            }
        }
    }

    /**
     * 上传车辆照片
     */
    public void uploadCarPhoto(final int step) {
        Photo[] photos = GlobalInfo.draft.photo;
        photoCount = 0;
        isUpSucceed = true;

        for(Photo photo : photos)
            if(photo!=null)
                photoCount++;

        for(final Photo photo : photos) {
            if(photo == null)
                continue;

            UploadPicUtil.UpSinglePicCallback callback = new UploadPicUtil.UpSinglePicCallback() {
                @Override
                public void uploadCallback(boolean isSucceed, String result, String moduleName) {
                    photoCount--;
                    if(isSucceed) {
                        photo.pic_url = result;
                    } else {
                        isUpSucceed = false;
                    }

                    if(photoCount <= 0) // 图片上传全部完成
                        uploadNextStep(isUpSucceed, step);
                }
            };
            System.out.println("上传"+photo.name);
            upUtil.upSinglePic("", photo.pic_path, callback);
        }
    }

    /**
     * @param step
     * 1 漆面  2 外观  3 内饰  4 结构件  5 车辆照片  已完成
     */
    public void uploadNextStep(boolean succeed, int step) {
        if(!isUpSucceed) {
            ProgressDialogUtil.dismissProgressDlg();
            showFailDialog("检测照片上传失败，请重新提交");
            isUploading = false;
            return;
        }

        switch(step) {
            case 1:
                // 漆面上传完成
                System.out.println("=== 漆面 === OK");
                uploadPhoto(++step, GlobalInfo.draft.condition.guise);
                break;

            case 2:
                // 外观完成
                System.out.println("=== 外观 === OK");
                uploadPhoto(++step, GlobalInfo.draft.condition.interior);
                break;

            case 3:
                System.out.println("=== 内饰 === OK");
                uploadPhoto(++step, GlobalInfo.draft.accident.skeletons);
                break;

            case 4:
                System.out.println("=== 结构件 === OK");
                uploadCarPhoto(++step);
                break;

            case 5:
                // 车辆照片完成
                System.out.println("=== 车辆照片 === OK");
                submitBaseInfo();
                break;
        }
    }

    /**
     * 提交基本信息
     */
    public void submitBaseInfo() {
        Draft draft = GlobalInfo.draft;
        ConfigInfo configInfo = draft.condition.config_info;
        BaseInfo baseInfo = draft.base_info;
        Map<String, String> map = new HashMap<String, String>();
        map.put("app_name", GlobalInfo.APP_NAME);
        map.put("vin", configInfo.vin);
        map.put("brand_id", configInfo.brand_id+"");
        map.put("series_id", configInfo.series_id+"");
        map.put("model_id", configInfo.model_id+"");
        map.put("gearbox_type", configInfo.trans_type_key);
        map.put("displacement", configInfo.car_engines);
        map.put("emission_standards", baseInfo.use_info.emission_standards_key);
        map.put("transfer_need_buyer", baseInfo.trade_info.buyer_live_key);
        map.put("feature_tags", baseInfo.desc_info);
        map.put("card_time", baseInfo.use_info.card_time);
        map.put("kilometer", (Integer.valueOf(baseInfo.use_info.kilometer)*10000)+"");
        map.put("car_color", baseInfo.use_info.color_key);
        map.put("year_check_time", baseInfo.trade_info.year_check_time);
        map.put("safe_force_time", baseInfo.trade_info.insurance_time);
        map.put("transfer_num", baseInfo.trade_info.transfer_num_key);
        map.put("province", baseInfo.use_info.province_id+"");
        map.put("city", baseInfo.use_info.city_id+"");
        map.put("note", baseInfo.desc_info);
        map.put("mention_day", baseInfo.trade_info.mention_day);
        map.put("abs", configInfo.abs);
        map.put("airbag_num", configInfo.airbag);
        map.put("leather_seats", configInfo.leather_seats);
        map.put("electrically_window", configInfo.electrically_window);
        map.put("gps_navigator", configInfo.gps_navigator);
        map.put("booster_type", configInfo.booster_type);
        map.put("seat_electrically", configInfo.electrically_seat);
        map.put("air_conditioner", configInfo.air);
        map.put("rate_cruise", configInfo.auto_adapt_drive);
        map.put("back_mirror_electrically", configInfo.back_mirror_electrically);
        map.put("remote_control_key", configInfo.smart_key);
        map.put("dvd", configInfo.dvd);
        map.put("reverse_radar", configInfo.reverse_view);
        map.put("screen_split_show", configInfo.centre_console_lcd);
        map.put("variable_suspension", configInfo.variable_suspension);
        map.put("driver_tool", configInfo.tool);
        map.put("hub_material", configInfo.hub_material);
        map.put("front_tire_size", configInfo.front_tire_size);
        map.put("rear_tire_size", configInfo.rear_tire_size);
        map.put("spare_tire_size", configInfo.spare_tire);
        map.put("installation_project", configInfo.retro_items);
        map.put("naked_price", Arith.mul(Double.valueOf(baseInfo.attach_info.naked_car_price), 10000)+"");
        map.put("full_price", Arith.mul(Double.valueOf(baseInfo.attach_info.full_car_price), 10000)+"");
        map.put("is_invoice", baseInfo.attach_info.invoice_key);
        map.put("is_car_config", baseInfo.attach_info.config_form_key);
        map.put("config_photo", baseInfo.attach_info.config_form_url);

        List<PhotoEntity> list = new ArrayList<PhotoEntity>();
        PhotoEntity photoEntity = null;
        if("有".equals(draft.base_info.attach_info.config_form)) {
            photoEntity = new PhotoEntity();
            photoEntity.object_type = 1;
            photoEntity.file_path = draft.base_info.attach_info.config_form_url;
            photoEntity.note = "配置单";
        }

        photoEntity = new PhotoEntity();
        photoEntity.object_type = 1;
        photoEntity.file_path = draft.condition.paintPicUrl;
        photoEntity.note = "漆膜厚度示意图";

        photoEntity = new PhotoEntity();
        photoEntity.object_type = 1;
        photoEntity.file_path = draft.accident.skeletonPicUrl;
        photoEntity.note = "结构检测示意图";

        addPhotoEntity(list, GlobalInfo.draft.condition.paint_surface);   // 漆面
        addPhotoEntity(list, GlobalInfo.draft.condition.guise);   // 外观
        addPhotoEntity(list, GlobalInfo.draft.condition.interior);   // 内饰
        addSkeletonPhotoEntity(list);   // 结构件
        addCarPhotoEntity(list);    // 车辆照片
        map.put("photos_list", new Gson().toJson(list));

        Request req = HttpRequest.getRequest(HttpRequest.POST, Api.Action.CAR_PUBLISH_BASE, map,
                new Response.Listener<JsonObject>() {
                    @Override
                    public void onResponse(JsonObject response) {
                        int carId = response.get("id").getAsInt();
                        submitReport(carId);
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        isUploading = false;
                        ProgressDialogUtil.dismissProgressDlg();
                        T.showShort(PublishPhotoActivity.this, error.getMessage());
                    }
                });
        addQueue(req);
    }

    /**
     * 提交完整报告
     */
    public void submitReport(final int carId) {
        Map<String, String> map = new HashMap<String, String>();
        map.put("id", carId+"");
        map.put("data", new Gson().toJson(GlobalInfo.draft));
        Request req = HttpRequest.getRequest(HttpRequest.POST, Api.Action.PUBLISH_REPORT, map,
                new Response.Listener<JsonObject>() {
                    @Override
                    public void onResponse(JsonObject response) {
                        ProgressDialogUtil.dismissProgressDlg();
                        isUploading = false;
                        Intent it = new Intent(PublishPhotoActivity.this, PublishBidRuleActivity.class);
                        it.putExtra("carId", carId);
                        it.putExtra("publish", true);
                        startActivity(it);
                        GlobalInfo.dbHelper.deleteDraf(GlobalInfo.tempOwner);
                        ActivityManager.getInstance().clearAllActivity(null);
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        isUploading = false;
                        ProgressDialogUtil.dismissProgressDlg();
                        T.showShort(PublishPhotoActivity.this, error.getMessage());
                    }
                });
        addQueue(req);
    }

    private void addPhotoEntity(List<PhotoEntity> list, ResultIntArrayPics[] resultIntArrayPics) {
        for(ResultIntArrayPics arrayPic : resultIntArrayPics) {
            if (arrayPic == null)
                continue;

            for (int i = 0; i < arrayPic.pic_path_list.size(); i++) {
                PhotoEntity entity = new PhotoEntity();
                entity.object_type = 1;
                entity.file_path = arrayPic.pic_url_list.get(i);
                entity.note = arrayPic.name;
                list.add(entity);
            }
        }
    }

    private void addSkeletonPhotoEntity(List<PhotoEntity> list) {
        for (final Skeleton skeleton : GlobalInfo.draft.accident.skeletons) {
            if (skeleton == null) {
                continue;
            }
            for (int i = 0; i < skeleton.pic_path_list.size(); i++) {
                PhotoEntity entity = new PhotoEntity();
                entity.object_type = 1;
                entity.file_path = skeleton.pic_path_list.get(i);
                entity.note = skeleton.number;
                list.add(entity);
            }
        }
    }

    private void addCarPhotoEntity(List<PhotoEntity> list) {
        Photo[] photos = GlobalInfo.draft.photo;
        for(int i=0; i<photos.length; i++) {
            Photo photo = photos[i];
            if (photo == null)
                continue;

            PhotoEntity entity = new PhotoEntity();
            entity.object_type = i==1? 3 : 1;
            entity.file_path = photo.pic_url;
            entity.note = photo.name;
            list.add(entity);
        }
    }

    /**
     * 失败提示框
     */
    public void showFailDialog(String msg) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        AlertDialog dlg = builder.setMessage(msg)
                .setNegativeButton("确定", null)
                .create();
        dlg.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
        dlg.show();
    }
}
